package com.hh.jwtdemo;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class WordCountReader {
    public static Stats getStats(String filePath) throws IOException {
        try (InputStream fis = new FileInputStream(filePath)) {
            if (filePath.endsWith(".wps") || filePath.endsWith(".WPS")) {
                // 检查文件签名
                byte[] header = new byte[8];
                InputStream tempStream = new FileInputStream(filePath);
                int bytesRead = tempStream.read(header);
                tempStream.close();

                // 判断是否是 OLE2 (DOC) 或 OOXML (DOCX)
                boolean isDoc = bytesRead >= 4 &&
                        (header[0] == (byte) 0xD0 && header[1] == (byte) 0xCF && header[2] == (byte) 0x11 && header[3] == (byte) 0xE0);
                boolean isDocx = bytesRead >= 4 &&
                        (header[0] == (byte) 0x50 && header[1] == (byte) 0x4B && header[2] == (byte) 0x03 && header[3] == (byte) 0x04);

                // 如果是 .doc 格式
                if (isDoc) {
                    try (FileInputStream fis2 = new FileInputStream(filePath)) {
                        HWPFDocument hwpfDocument = new HWPFDocument(fis2);
                        return extractStatsFromHWPF(hwpfDocument);
                    }
                }
                // 如果是 .docx 格式
                else if (isDocx) {
                    try (FileInputStream fis3 = new FileInputStream(filePath)) {
                        XWPFDocument xwpfDocument = new XWPFDocument(fis3);
                        return extractStatsFromXWPF(xwpfDocument);
                    }
                }
                // 如果都不是
                else {
                    throw new IOException("不支持的文档格式，无法识别的 .wps 文件");
                }
            } else {
                throw new IllegalArgumentException("不支持的文件格式，仅支持.wps格式文件");
            }
        }
    }

    private static Stats extractStatsFromHWPF(HWPFDocument document) {
        StringBuilder textBuilder = new StringBuilder();
        String[] paragraphs = document.getDocumentText().split("\r\n");
        for (String paragraph : paragraphs) {
            textBuilder.append(paragraph).append("\n");
        }
        return calculateStats(textBuilder.toString());
    }

    private static Stats extractStatsFromXWPF(XWPFDocument document) {
        StringBuilder textBuilder = new StringBuilder();
        
        // 处理段落
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            String paragraphText = paragraph.getText();
            if (paragraphText != null && !paragraphText.trim().isEmpty()) {
                textBuilder.append(paragraphText).append("\n");
            }
        }
        
        // 处理表格
        for (XWPFTable table : document.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    String cellText = cell.getText();
                    // 增加对单元格是否为空的判断
                    if (cellText != null && !cellText.trim().isEmpty() && !isTableCellEmpty(cell)) {
                        textBuilder.append(cellText).append("\n");
                    }
                }
            }
        }
        
        return calculateStats(textBuilder.toString());
    }
    
    // 新增方法：判断表格单元格是否为空
    private static boolean isTableCellEmpty(XWPFTableCell cell) {
        // 检查单元格内容是否为空或者只包含空格
        if (cell.getText() == null || cell.getText().trim().isEmpty()) {
            return true;
        }
        
        // 检查单元格是否包含图片等非文本内容
        if (!cell.getParagraphs().isEmpty()) {
            for (XWPFParagraph paragraph : cell.getParagraphs()) {
                if (!paragraph.getRuns().isEmpty()) {
                    for (XWPFRun run : paragraph.getRuns()) {
                        if (run.getEmbeddedPictures().size() > 0) {
                            return true; // 包含图片
                        }
                    }
                }
            }
        }
        
        return false;
    }

    private static Stats calculateStats(String text) {
        // 新增文本清理：移除控制字符，保留可见字符
        text = text.replaceAll("[\\p{Cntrl}&&[^\n\r\t]]", ""); // 移除控制字符，保留换行符、回车符和制表符
        
        // 预处理：替换全角空格和零宽空格，保留空格
        text = text.replaceAll("[\\u3000\\u200b]", " ");
        
        // 统计字符数（不计空格）- 排除所有空白字符包括空格、制表符、换行符等
        int charCountNoSpaces = text.replaceAll("\\s", "").length();
        
        // 统计字符数（计空格但不包括换行符和制表符）- 更精确地匹配WPS统计方式
        int charCountWithSpaces = text.replace("\n", "").replace("\r", "").replace("\t", "").length();
        
        // 统计段落数 - 改进为只计算非空段落
        int paragraphCount = 0;
        if (text.trim().length() > 0) {
            String[] paragraphs = text.split("\n");
            for (String paragraph : paragraphs) {
                if (paragraph.trim().length() > 0) {
                    paragraphCount++;
                }
            }
        }
        
        // 统计非中文单词数 - 改用更严格的正则表达式
        int nonChineseWordCount = countNonChineseWords(text);
        
        // 统计中文字符数
        int chineseCharCount = countChineseCharacters(text);
        
        // 总字数 = 中文字符数 + 非中文单词数
        int wordCount = chineseCharCount + nonChineseWordCount;

        return new Stats(wordCount, charCountNoSpaces, charCountWithSpaces, paragraphCount, nonChineseWordCount, chineseCharCount);
    }

    // 判断是否为中文字符或全角符号
    private static boolean isChinese(char c) {
        return (c >= 0x4E00 && c <= 0x9FFF) ||      // 常用汉字
               (c >= 0x3400 && c <= 0x4DBF) ||      // 扩展A区
               (c >= 0xF900 && c <= 0xFAFF) ||      // 兼容汉字
               (c >= 0x20000 && c <= 0x2A6DF) ||    // 扩展B区
               (c >= 0xFF00 && c <= 0xFFEF) ||      // 全角ASCII、全角标点
               (c >= 0x3000 && c <= 0x303F) ||      // 中文标点符号
               (c >= 0x2E80 && c <= 0x2EFF) ||      // 汉字笔画扩展
               (c >= 0x2F00 && c <= 0x2FDF) ||      // 汉字部首扩展
               (c >= 0x31C0 && c <= 0x31EF);        // 汉字部件扩展
    }

    // 统计中文字符数量
    private static int countChineseCharacters(String text) {
        int count = 0;
        for (char c : text.toCharArray()) {
            if (isChinese(c)) {
                count++;
            }
        }
        return count;
    }

    // 修改 countNonChineseWords 方法逻辑，不再使用正则匹配单词，而是以空白符分隔，统计每个非空白连续字符块为一个“字”
    private static int countNonChineseWords(String text) {
        if (text == null || text.isEmpty()) {
            return 0;
        }

        int count = 0;
        boolean inWord = false;
        for (char c : text.toCharArray()) {
            if (!Character.isWhitespace(c)) {
                if (!inWord) {
                    count++; // 开始一个新的“字”
                    inWord = true;
                }
            } else {
                inWord = false;
            }
        }
        return count;
    }

    public static class Stats {
        public final int wordCount;
        public final int charCountNoSpaces;
        public final int charCountWithSpaces;
        public final int paragraphCount;
        public final int nonChineseWordCount;
        public final int chineseCharCount;

        public Stats(int wordCount, int charCountNoSpaces, int charCountWithSpaces, int paragraphCount, int nonChineseWordCount, int chineseCharCount) {
            this.wordCount = wordCount;
            this.charCountNoSpaces = charCountNoSpaces;
            this.charCountWithSpaces = charCountWithSpaces;
            this.paragraphCount = paragraphCount;
            this.nonChineseWordCount = nonChineseWordCount;
            this.chineseCharCount = chineseCharCount;
        }

        @Override
        public String toString() {
            return "Stats{" +
                    "wordCount=" + wordCount +
                    ", charCountNoSpaces=" + charCountNoSpaces +
                    ", charCountWithSpaces=" + charCountWithSpaces +
                    ", paragraphCount=" + paragraphCount +
                    ", nonChineseWordCount=" + nonChineseWordCount +
                    ", chineseCharCount=" + chineseCharCount +
                    '}';
        }
    }
}